<template>
  <el-card>
    <!-- 标题区 + 按钮 -->
    <template #header>
      <div class="flex-between">
        <span>医生排班管理</span>
        <div>
          <el-button type="primary" @click="openDialog()">新增排班</el-button>
          <el-button type="success" @click="openGenDialog()">批量生成</el-button>
        </div>
      </div>
    </template>

    <!-- 查询区 -->
    <el-form :inline="true" class="mb-3">
      <el-form-item label="日期">
        <el-date-picker
            v-model="query.date"
            type="date"
            placeholder="选择日期" clearable
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="科室ID">
        <el-input v-model="query.deptid" placeholder="科室ID" clearable style="width:140px"/>
      </el-form-item>
      <el-form-item label="医生ID">
        <el-input v-model="query.userid" placeholder="医生ID" clearable style="width:140px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadData()">查询</el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table :data="tableData" stripe border style="width:100%">
      <el-table-column prop="id"        label="ID"        width="70"/>
      <el-table-column prop="scheddate" label="排班日期" width="120"/>
      <el-table-column prop="noon"      label="时段"/>
      <el-table-column prop="deptid"    label="科室ID"/>
      <el-table-column prop="userid"    label="医生ID"/>
      <el-table-column prop="ruleid"    label="规则ID"/>
      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button size="small" type="primary" @click="openDialog(row)">编辑</el-button>
          <el-button size="small" type="danger"  @click="remove(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="mt-3 text-right">
      <el-pagination
          :current-page="query.page"
          :page-size="query.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5,10,20,50]"
          @current-change="p=>{query.page=p;loadData()}"
          @size-change="s=>{query.pageSize=s;loadData()}"
      />
    </div>
  </el-card>

  <!-- 新增 / 编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" @close="formRef?.clearValidate()">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item prop="scheddate" label="排班日期">
        <el-date-picker v-model="form.scheddate" type="date" placeholder="选择日期"/>
      </el-form-item>
      <el-form-item prop="noon" label="时段">
        <el-select v-model="form.noon" placeholder="请选择">
          <el-option label="上午" value="上午"/>
          <el-option label="下午" value="下午"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="deptid" label="科室ID">
        <el-input v-model="form.deptid"/>
      </el-form-item>
      <el-form-item prop="userid" label="医生ID">
        <el-input v-model="form.userid"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="save()">确认</el-button>
    </template>
  </el-dialog>

  <!-- 批量生成排班弹窗 -->
  <el-dialog v-model="genVisible" title="批量生成排班" width="400px">
    <el-form :model="genForm" :rules="genRules" ref="genRef" label-width="100px">
      <el-form-item prop="start" label="开始日期">
        <el-date-picker v-model="genForm.start" type="date" placeholder="选择日期"/>
      </el-form-item>
      <el-form-item prop="end" label="结束日期">
        <el-date-picker v-model="genForm.end" type="date" placeholder="选择日期"/>
      </el-form-item>
      <el-form-item prop="ruleids" label="规则ID集">
        <el-input v-model="genForm.ruleids" placeholder="例：1,2,3"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="genVisible=false">取消</el-button>
      <el-button type="primary" @click="generate()">生成</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'

/* entity 前缀 */
const entity = 'schedule'

/* 查询参数 */
const query = reactive({ date:'', deptid:'', userid:'', page:1, pageSize:10 })
const tableData = ref<any[]>([])
const total     = ref(0)

/* 单条排班弹窗数据 */
const dialogVisible = ref(false)
const dialogTitle   = ref('新增排班')
const form          = reactive<any>({id:undefined, scheddate:'', noon:'上午', deptid:'', userid:'', ruleid:null})
const formRef       = ref<FormInstance>()
const rules = {
  scheddate:[{required:true,message:'必选',trigger:'change'}],
  noon:[{required:true,message:'必选',trigger:'change'}],
  deptid:[{required:true,message:'必填',trigger:'blur'}],
  userid:[{required:true,message:'必填',trigger:'blur'}],
}

/* 生成排班弹窗数据 */
const genVisible = ref(false)
const genForm    = reactive({ start:'', end:'', ruleids:'' })
const genRef     = ref<FormInstance>()
const genRules   = {
  start:[{required:true,message:'必选',trigger:'change'}],
  end:[{required:true,message:'必选',trigger:'change'}],
  ruleids:[{required:true,message:'必填',trigger:'blur'}],
}

/* CRUD */
async function loadData(){
  const {data} = await axios.get(`/api/master/${entity}`,{params:query})
  tableData.value = data.records
  total.value     = data.total
}
function reset(){ Object.assign(query,{date:'',deptid:'',userid:'',page:1}); loadData() }

function openDialog(row?:any){
  if(row){ Object.assign(form,row); dialogTitle.value='编辑排班' }
  else   { Object.assign(form,{id:undefined,scheddate:'',noon:'上午',deptid:'',userid:'',ruleid:null}); dialogTitle.value='新增排班' }
  dialogVisible.value=true
}
async function save(){
  await formRef.value?.validate()
  if(form.id){
    await axios.put(`/api/master/${entity}/${form.id}`,form)
    ElMessage.success('更新成功')
  }else{
    await axios.post(`/api/master/${entity}`,form)
    ElMessage.success('新增成功')
  }
  dialogVisible.value=false
  loadData()
}
async function remove(row:any){
  try{
    await ElMessageBox.confirm('确认删除?','提示',{type:'warning'})
    await axios.delete(`/api/master/${entity}/${row.id}`)
    if(tableData.value.length===1 && query.page>1) query.page--
    ElMessage.success('删除成功')
    loadData()
  }catch{}
}

/* 批量生成 */
function openGenDialog(){
  Object.assign(genForm,{start:'',end:'',ruleids:''})
  genVisible.value=true
}
async function generate(){
  await genRef.value?.validate()
  const ruleIdsArr = genForm.ruleids.split(',').map(id=>id.trim()).filter(Boolean)
  await axios.post(`/api/master/${entity}/generate`,{
    start:genForm.start,
    end:genForm.end,
    ruleIds:ruleIdsArr
  })
  ElMessage.success('生成完成')
  genVisible.value=false
  loadData()
}

onMounted(loadData)
</script>

<style scoped>
.flex-between{display:flex;justify-content:space-between;align-items:center}
.mb-3{margin-bottom:12px}
.mt-3{margin-top:12px}
.text-right{text-align:right}
</style>
